<?php
// +----------------------------------------------------------------------
// | 分销联盟数据处理
// +----------------------------------------------------------------------
// | Author: TongBC <50249101@qq.com>
// +----------------------------------------------------------------------
// | Date  : 2015/03/06
// +----------------------------------------------------------------------
include("/var/www/html/new/com.inc.php");
include('/var/www/html/new/d/common/autoload.php');
include('/var/www/html/new/d/class/MemberAccount.class.php');
include('/var/www/html/new/d/class/Alliance.class.php');
include('/var/www/html/new/d/class/Member.php');
include('/var/www/html/new/d/class/abc/Syslog.class.php');
include('/var/www/html/new/d/class/abc/Member.class.php');

$ac=$GLOBALS['_ac'];
$pw=$GLOBALS['_pw'];
$s = new SoapClient(null,array("location" => "http://localhost/open/openService/pft_insideMX.php","uri" => "www.16u.com?ac_16u=$ac|pw_16u=$pw|auth_16u=true"));

$action = trim($_REQUEST['action']);
if($action=='register'){
    if($_SESSION['sid']!=1) exit('{"status":"fail","mesg":"非法访问"}');
}


switch($action) {
	// 注册联盟
	case 'register':
		// 1.注册平台账号
		$dataMain    = array();
        $dataExtInfo = array();
		$data = _addslashes($_REQUEST);
		$dataMain['dname'] = $data['company'];
		if(empty($dataMain['dname'])) exit('{"status":"fail","msg":"联盟名称不能为空"}');
		
		$dataMain['cname'] = safetxt($data['contact']);
		if(!is_chinese($dataMain['cname'])) exit('{"status":"fail","msg":"姓名仅限中文汉字"}');
		
		$dataMain['mobile'] = safetxt($data['mobile']);
        if(!ismobile($dataMain['mobile'])) exit('{"status":"fail","msg":"手机号格式不正确"}');
		
		if(!empty($data['g_tel'])) {
            $dataMain['ctel'] = safetxt($data['g_tel']);
            // if(isphone($dataMain['ctel'])) exit('{"status":"fail","msg":"固定电话格式不正确"}');
        }
		
		if($data['password']!=$data['confirmPwd']) exit('{"status":"fail","msg":"密码不一致"}');
		if((chkPassword($data['password'], $data['confirmPwd']))!=1) exit('{"status":"fail","msg":"密码格式不正确"}');
		
		$dataMain['password'] = md5(md5($data['password']));

        $dataMain['dtype'] = 0;
        $dataMain['status'] = 0;
		
		if($data['splitting']>15) exit('{"status":"fail","msg":"平台比例过大，超过15请联系技术员"}');
		// 检测是否存在联盟名称
		$sql="select id from `pft_distributor_union_SE` WHERE dtitle='".$dataMain['dname']."' limit 1";
		$GLOBALS['le']->query($sql);
		if($GLOBALS['le']->fetch_assoc()) exit('{"status":"fail","msg":"联盟名称已存在"}');
	
		$mem = new pft\member\MemberAccount($GLOBALS['le']);
        $result = $mem->register($dataMain);
		if($result['status']!='ok') exit('{"status":"fail","msg":"'.$result['msg'].'"}');
		
		// 2.创建联盟
		$ave = floor((100 - $data['splitting']) / 6);
		$last = 100 - ($ave * 5) - $data['splitting'];
		$ratio[] = $data['splitting'];
		for($i=0;$i<5;$i++) $ratio[] = $ave;
		$ratio[] = $last;
		$dratio = implode('|', $ratio);
		$tmp = explode('|',$result['body']);
        $fid = $tmp[0];
        // $fid = 1433;
		$sql="insert into `pft_distributor_union_SE` set fid='$fid',dtitle='{$data['company']}',dratio='{$dratio}',dratio_default='{$dratio}',protocol='',dmemo='',createtime=now(),dstatus=0";
		// echo $sql;
		if($GLOBALS['le']->query($sql)){
			exit('{"status":"success","msg":"联盟创建成功，账号：'.$tmp[1].'"}');
		}
		exit('{"status":"fail","msg":"联盟创建失败"}');
		break;
	// 更改资料
	case 'modify_s':
	
		$id = $_REQUEST['id'] + 0;// 联盟ID
		$name = _addslashes($_REQUEST['dname']);// 联盟名称
		$platform = $_REQUEST['platform'] + 0;// 平台比例
		
		if($name=='') exit('{"status":"fail","msg":"联盟名称不能为空"}');
		if($platform > 50) exit('{"status":"fail","msg":"平台比例不能大于50%"}');
		
		// 检测是否存在联盟名称
		$sql="select id from `pft_distributor_union_SE` WHERE dtitle='".$name."' limit 1";
		$GLOBALS['le']->query($sql);
		if($GLOBALS['le']->fetch_assoc()){
			if($id!=$GLOBALS['le']->f('id')) exit('{"status":"fail","msg":"联盟名称已存在"}');
		}
		
		// 利润比例
		
		$ave = floor((100 - $platform) / 6);
		$last = 100 - ($ave * 5) - $platform;
		$ratio[] = $platform;
		for($i=0;$i<5;$i++) $ratio[] = $ave;
		$ratio[] = $last;
		$dratio = implode('|', $ratio);
		
		// 执行更改操作
		$sql = "update pft_distributor_union_SE set dtitle='$name',dratio='$dratio' where id=$id limit 1";
		if($GLOBALS['le']->query($sql)){
			exit('{"status":"success","msg":"更新成功"}');
		}
		exit('{"status":"fail","msg":"更新失败"}');
		break;

    // 联盟资料表编辑
    case 'modify':

		$data = _addslashes($_POST);
        $alliance = new Alliance();
        if($alliance->chExistsName($data['alliName'],$data['uid'])) exit('{"status":"fail","mesg":"联盟名称已存在"}');

        // 平台|供应商|盟主|省代|市代|上级邀请人|邀请人
		$ratio[] = $data['profit_a'] ? $data['profit_a']+0:0;
        $ratio[] = $data['profit_b'] ? $data['profit_b']+0:0;
		$ratio[] = $data['profit_c'] ? $data['profit_c']+0:0;
		$ratio[] = $data['profit_d'] ? $data['profit_d']+0:0;
		$ratio[] = $data['profit_e'] ? $data['profit_e']+0:0;
		$ratio[] = $data['profit_f'] ? $data['profit_f']+0:0;
		$ratio[] = $data['profit_g'] ? $data['profit_g']+0:0;

		if(array_sum($ratio)!=100) exit('{"status":"fail","mesg":"利润比例不等于100"}');
		
        // 押金设置 以分为单位
		$pledge = array();
		$pledge[] = ($data['cash_pledge_gx'] + 0) * 100;
		$pledge[] = ($data['cash_pledge_gy'] + 0) * 100;
		$pledge[] = ($data['cash_pledge_fx'] + 0) * 100;
		$aData['cash_pledge'] = implode("|",$pledge);
		
        $aData['dratio'] = implode('|', $ratio);
        $aData['dtitle'] = safetxt($data['alliName']);
        $aData['id'] = $data['uid'] + 0;
		$aData['protocol'] = $data['protocol'];
		
		$fid = $_SESSION['sid'];
		
		$sql="update `pft_distributor_union_SE` set `dtitle`='{$aData['dtitle']}',`dratio`='{$aData['dratio']}',`dmemo`='{$aData['dmemo']}',protocol='{$aData['protocol']}',`cash_pledge`='{$aData['cash_pledge']}' where id={$aData['id']} and fid=$fid limit 1";
        if($GLOBALS['le']->query($sql)) exit('{"status":"success","mesg":"更新成功"}');
		exit('{"status":"fail","mesg":"其他错误"}');
        break;
	// 更改联盟状态
	case 'change_s':
		$status = $_REQUEST['status'] + 0;
		$id = $_REQUEST['id'] + 0;
		$sql = "update pft_distributor_union_SE set dstatus=$status where id=$id limit 1";
		echo $GLOBALS['le']->query($sql) ? '200':'100';
		break;
	// 指定代理
	case 'agent_set':
	

		$rid = $_REQUEST['rid'] + 0;// 表ID
		$nCode = $_REQUEST['ac'] + 0;// 城市代码
		$agent_id = $_REQUEST['agent'] + 0;// 代理商
		$date = date('Y-m-d H:i:s');// 指定时间
		$sid = $_SESSION['sid'];// 联盟账号ID
		$response = array('status'=>'fail','mesg'=>'指定代理商失败');
		
		// 获取城市信息
		$sql = "select n_code,province,city,parent_province from pft_area_code_concat where n_code=$nCode limit 1";
		$GLOBALS['le']->query($sql);
		$data = $GLOBALS['le']->fetch_assoc();
		if(!$data) exit('{"status":"fail","mesg":"不存在城市"}');
		$title = ($data['n_code']==$data['parent_province']) ? $data['province']:$data['city'];
		
		// 指定代理商
		$sql = "select id,inviterID from pft_distributor_agency where fid=$sid and darea_code=$nCode limit 1";
		$GLOBALS['le']->query($sql);
		if($GLOBALS['le']->fetch_assoc()){// 已指定
			$id = $GLOBALS['le']->f('id');
			$upd = "update pft_distributor_agency set inviterID=$agent_id,dstatus=0,darea_title='$title',dtime='$date' where id=$id limit 1";
			if($GLOBALS['le']->query($upd)){
				$response['status'] = 'success';
				$response['mesg'] = '成功指定代理商';
				$response['rid'] = $rid;
				$response['date']= $date;	
			}
		}else{
			$ins = "insert into pft_distributor_agency set fid=$sid,darea_title='$title',darea_code='$nCode',inviterID='$agent_id',dstatus=0,dtime='$date'";
			if($GLOBALS['le']->query($ins)){
				$response['status'] = 'success';
				$response['mesg'] = '成功指定代理商';
				$response['rid'] = $rid;
				$response['date']= $date;	
			}
		}
		exit(json_encode($response));
		break;
	// 清除代理商
	case 'agent_clear':
		$id = $_REQUEST['rid'] + 0;
		$upd = "update pft_distributor_agency set dstatus=1 where id=$id and fid={$_SESSION['sid']} limit 1";
		$result = $GLOBALS['le']->query($upd) ? 'success':'fail';
		exit('{"code":"'.$result.'"}');
		break;
	// 获取代理，当 ac 传值获取市代理
	case 'agents':
		$reData = array();
		$nCode = $_REQUEST['ac'] + 0 ;
		$condition = ($nCode>0) ? "parent_province='$nCode' and parent_province<>n_code" : "parent_province=n_code";
		$sql = "select province,n_code,city from pft_area_code_concat where $condition";
		// echo $sql;
		$GLOBALS['le']->query($sql);
		while($row = $GLOBALS['le']->fetch_assoc()){
			$row['agent'] = 0;
			$reData[$row['n_code']] = $row;
		}
		
		// 2.获取代理
		if(count($reData)){
			$nCodes = implode(',', array_keys($reData));
			$sql = "select inviterID,darea_code from `pft_distributor_agency` where `fid`={$_SESSION['sid']} and darea_code in ($nCodes)";
			$GLOBALS['le']->query($sql);
			while($row = $GLOBALS['le']->fetch_assoc()){
				if(isset($reData[$row['darea_code']]))
					$reData[$row['darea_code']]['agent'] = $row['inviterID'];
			}	
		}
		
		echo json_encode($reData);
		break;
	// 获取当前已指定的代理商
	case 'agents_s':
		$memberID = $_SESSION['sid'];
		// 获取省份
		$sql="select n_code,province from `pft_area_code_concat` where parent_province=n_code";
		$GLOBALS['le']->query($sql);
		while($row = $GLOBALS['le']->fetch_assoc()){
			$province[$row['n_code']] = $row;
		}

		$agents = array();
		$sql="select d.darea_title,d.dtime,m.dname,d.darea_code,d.inviterID from pft_distributor_agency d left join pft_member m on d.inviterID=m.id where fid=$memberID";
		$GLOBALS['le']->query($sql);
		while($row=$GLOBALS['le']->fetch_assoc()){
			if(isset($province[$row['darea_code']])){
				$agents['province'][] = $row;
			}else{
				$agents['city'][] = $row;
			}
		}
		echo json_encode($agents);
		break;
    // 退出会员（status = 1）
    case 'out':
		$mid = $_REQUEST['mid'];
		$sid = $_SESSION['sid'];
		$upd = "update `pft_union_member_info_SE` set dstatus=1 where fid=$sid and memberID=$mid limit 1";
		if($GLOBALS['le']->query($upd)){
			// 断连供应商分销商关系
			$mem = new pft\Member\MemberAccount($GLOBALS['le']);
			$result = $mem->RelationHanler(pft\Member\MemberAccount::RELATION_REMOVE, $_SESSION['sid'], $mid);
			exit(json_encode($result));
		}
		exit('{"status":"fail","msg":"删除失败"}');
        break;
	// 会员申请加入联盟
	case 'apply':
		// print_r($_REQUEST);
		// exit;
		$mid = $_SESSION['sid'] + 0;// 会员ID
		$aid = $_REQUEST['aid'] + 0;// 联盟ID
		
		if(isset($_REQUEST['aid'])){
			$aid = $_REQUEST['aid']+0;
		}else{
			if($_REQUEST['pto']!='on') exit('同意协议才允许加入');
		}
		
		
		
		$sql="select id,fid from `pft_distributor_union_SE` where id=$aid limit 1";
		$GLOBALS['le']->query($sql);
		if(!$GLOBALS['le']->fetch_assoc()) exit('{"status":"fail","mesg":"联盟不存在"}');
		$fid = $GLOBALS['le']->f('fid');
		if($mid==$fid) exit('{"status":"fail","mesg":"自己不允许加入自己创建的联盟"}');
		
		// 1.建立分销、供应关系
		// if($_REQUEST['us']!=1 && $_REQUEST['ud']!=1){
			// exit('{"status":"fail","mesg":"请选择成为供应商或分销商"}');
		// }
		
		if($_REQUEST['us']==1){
			if(!relationship($fid, $mid)) exit('{"status":"fail","mesg":"供应关系确立失败，请重试"}');
		}
		// if($_REQUEST['ud']==1){}
		if(!relationship($mid, $fid)) exit('{"status":"fail","mesg":"分销关系确立失败，请重试"}');
		
		
		
		// 2.加入联盟
		if(!coalize($mid,$fid)) exit('{"status":"fail","mesg":"加入失败，请重试"}');
		
	
		// 3.1设置自己供应产品购买
		$sql="select id,pids,status from `pft_product_sale_list` where aid=$fid and fid=$mid limit 1";
		$GLOBALS['le']->query($sql);
		if($GLOBALS['le']->fetch_assoc()){
			if($GLOBALS['le']->f('pids')!='A' || $GLOBALS['le']->f('status')!=0){
				$id = $GLOBALS['le']->f('id');
				$upd="update `pft_product_sale_list` set `status`=0,`pids`='A' where id=$id and aid=$fid and fid=$mid limit 1";
				$GLOBALS['le']->query($upd);
			}
		}else{
			$ins = "insert into `pft_product_sale_list` (fid,aid,pids) values ($mid,$fid,'A')";
			$GLOBALS['le']->query($ins);
		}
		
		// 3.2配置转分销产品购买权限
		$sql="select * from `pft_p_apply_evolute` where fid=$fid and status=0 and active=1 and sourceid<>$mid and sid<>$mid";
		$GLOBALS['le']->query($sql);
		while($row = $GLOBALS['le']->fetch_assoc()){
			// 供应链存在该分销商
			if(in_array($mid, explode(',', $row['aids']))) continue;
			$evolute[$row['pid']] = array(
				'aids'=>$row['aids'],
				'pid'=>$row['pid'],
				'sid'=>$row['sid'],
				'sourceid'=>$row['sourceid'],
				'lvl'=>$row['lvl'],
			);
		}
		
		$sets = array();// 获取已经设置的记录
		$sql = "select pid,status,id from `pft_p_apply_evolute` where sid=$fid and fid=$mid";
		$GLOBALS['le']->query($sql);
		while($row = $GLOBALS['le']->fetch_assoc()){
			$sets[$row['pid']] = $row;
		}
		
		// 3.3为分销商设置自己可购买转分销产品
		$ins_f = false; $upd_a = array();
		if(count($evolute)){
			$ins = "insert into `pft_p_apply_evolute` (fid,sid,aids,sourceid,pid,lvl,rectime) values ";
			foreach($evolute as $pid=>$data){
				if(isset($sets[$pid])){
					if($sets[$pid]['status']==1){
						$upd_a[] = $sets[$pid]['id'];
					} 
					continue;
				}
				// 没有配置，新增
				$lvl = $data['lvl'] + 1;
				$aids = $data['aids'].','.$fid;
				$ins.="($mid,$fid,'$aids',{$data['sourceid']},$pid,$lvl,now()),";
				$ins_f = true;
			}
			if($ins_f) $GLOBALS['le']->query(rtrim($ins, ','));
		}
		
		if(($size = count($upd_a))){
			$ids = implode(',', $upd_a);
			$upd = "update pft_p_apply_evolute set status=0 where id in ($ids) limit $size";
			$GLOBALS['le']->query($upd);
		}
		exit('{"status":"success","mesg":"加入成功"}');
		break;
	// 联盟信息
	case 'infomation':
		$aid = $_REQUEST['aid'] + 0;
		$sql="select /*id,dtitle,dstatus,*/protocol,cash_pledge from `pft_distributor_union_SE` where id=$aid limit 1";
        $GLOBALS['le']->query($sql);
		$a_info = $GLOBALS['le']->fetch_assoc();
        $cash_pledge = explode('|',$a_info['cash_pledge']);
        $a_info['cash_pledge0'] = $cash_pledge[0] ? $cash_pledge[0]/100: 0;
        $a_info['cash_pledge1'] = $cash_pledge[1] ? $cash_pledge[1]/100: 0;
        $a_info['cash_pledge2'] = $cash_pledge[2] ? $cash_pledge[2]/100: 0;
		echo json_encode(array('code'=>100,'data'=>$a_info));
		break;
	// 会员提交申请进入联盟
	case 'apply_union':

		// 1.基本情况判断
		$aid = $_POST['aid'] + 0;// 联盟ID
		$mid = $_SESSION['sid']; // 会员ID
		
		// 申请身份
		$identity = 0; // 1 供销商 2 供应商 3 分销商
		if(isset($_REQUEST['us']) && $_REQUEST['us']==1) $identity=2;
		if(isset($_REQUEST['ud']) && $_REQUEST['ud']==1) $identity=3;
		if(isset($_REQUEST['ud']) && isset($_REQUEST['us'])) $identity=1;
		if($identity==0) exit('{"status":"fail","mesg":"请选择申请加入的联盟身份"}');
		
		
		if($aid==0) exit('{"status":"fail","msg":"参数错误"}');// 没传递联盟ID参数
		
		if($_REQUEST['pto']!='1') exit('{"status":"fail","msg":"请先阅读协议并同意"}');
		
		$sql = "select id,fid,cash_pledge from `pft_distributor_union_SE` where id=$aid limit 1";
		$GLOBALS['le']->query($sql);
		if(!$GLOBALS['le']->fetch_assoc()) exit('{"status":"fail","mesg":"联盟不存在"}');
		
		$deposit = $GLOBALS['le']->f('cash_pledge');// 
		$fid = $GLOBALS['le']->f('fid');
		
		if($sid==$fid) exit('{"status":"fail","mesg":"自己不允许加入自己创建的联盟"}');

		// 是否资质认证
		$sql = "select certi_status from pft_member_extinfo where fid=$mid limit 1";
		$GLOBALS['le']->query($sql);
		if(!$GLOBALS['le']->fetch_assoc()) exit('{"status":"fail","mesg":"账号信息出错"}');
		if($GLOBALS['le']->f('certi_status')!=2) exit('{"status":"fail","mesg":"您未通过资质认证","code":101}');
		
		// 是否已申请   类型|押金|状态   0 未交 1 已交
		$deposit_a = explode('|', $deposit);
		$dmoney = $deposit_a[($identity-1)];// 需缴纳押金
//		$roleDt = $identity.'|'.$dmoney.'|0';
        $roleDt = $identity.'|0|0';
		
		$union_id = 0;
		$sql = "select id,dstatus,role_pledge from pft_union_member_info_SE where fid=$fid and memberID=$mid limit 1";
		$GLOBALS['le']->query($sql);
		if($GLOBALS['le']->fetch_assoc()){
			$dstatus  = $GLOBALS['le']->f('dstatus');
			$union_id = $GLOBALS['le']->f('id');
			if($dstatus== '0') exit('{"status":"fail","mesg":"您已通过审核，请勿重复提交"}');
			if($dstatus== '2') exit('{"status":"fail","mesg":"您的申请已递交，请勿重复申请"}');
			// if($dstatus==4) exit('{"status":"fail","mesg":"您已被禁止加入该联盟，请联系联盟发起人"}');
			$deposit_arr = explode('|', $GLOBALS['le']->f('role_pledge'));
			if($deposit_arr[2]==1) exit('{"status":"fail","mesg":"盟主未退还押金，请先联系盟主退还押金后申请"}');
		}

		if($union_id==0){
			$sql = "insert into  pft_union_member_info_SE set dstatus=2,role_pledge='$roleDt',fid=$fid,memberID=$mid,jointime=now()";
			if($GLOBALS['le']->query($sql)) exit('{"status":"success","mesg":"申请成功"}');
			exit('{"status":"fail","mesg":"申请失败"}');
		}

		$sql = "update pft_union_member_info_SE set dstatus=2,role_pledge='$roleDt',jointime=now() where id=$union_id and fid=$fid limit 1";
		if($GLOBALS['le']->query($sql)) exit('{"status":"success","mesg":"申请成功"}');
		exit('{"status":"fail","mesg":"申请失败"}');
		break;
		
	// 审核操作
	case 'audit_do':
		$fid   = $_SESSION['sid'] + 0;        // 联盟盟主ID
		$mid   = $_REQUEST['mid'] + 0;        // 会员ID
		$msg   = $_REQUEST['msg'];            // 驳回消息
		$state = $_REQUEST['status'] + 0;     // 审核状态

        audit_do:
		$sql = "select id,dstatus,role_pledge from pft_union_member_info_SE where fid=$fid and memberID=$mid order by id desc limit 1";
		$GLOBALS['le']->query($sql);
		if(!$GLOBALS['le']->fetch_assoc()) exit('{"status":"fail","msg":"记录不存在"}');
		
		$roleDt   = $GLOBALS['le']->f('role_pledge');
		$dstatus  = $GLOBALS['le']->f('dstatus');
		$union_id = $GLOBALS['le']->f('id');
		$deposit  = explode('|', $roleDt);
		$dmoney   = $deposit[1];// 退还押金金额
		
		
		if($state==1 || $state==3){// 驳回与退出
		
			if($state==1){
				
				// 断连供应商分销商关系
				$mem = new pft\Member\MemberAccount($GLOBALS['le']);
				if($deposit[0]==1 || $deposit[0]==2) $mem->RelationHanler(pft\Member\MemberAccount::RELATION_REMOVE, $mid, $fid);
				if($deposit[0]==1 || $deposit[0]==3) $mem->RelationHanler(pft\Member\MemberAccount::RELATION_REMOVE, $fid, $mid);
				$sql = "update pft_union_member_info_SE set dstatus=1,ref_reason='' where id=$union_id limit 1";
				if($GLOBALS['le']->query($sql)) exit('{"status":"success","msg":"退出成功"}');
				exit('{"status":"fail","msg":"退出失败"}');
			}else{
				$sql = "update pft_union_member_info_SE set dstatus=3,ref_reason='$msg' where id=$union_id and memberID=$mid limit 1";
				if($GLOBALS['le']->query($sql)) exit('{"status":"success","msg":"驳回成功"}');
				exit('{"status":"fail","msg":"驳回失败"}');
			}
			
		}else{
			
			if($dstatus!=2) exit('{"status":"fail","msg":"不存在需要审核的记录"}');
			// print_r($deposit);
			$mem = new pft\Member\MemberAccount($GLOBALS['le']);
			// 根据不同角色设置产品权限 1 供销商 2 供应商 3 分销商			
			if($deposit[0]==1 || $deposit[0]==2){
				abc777\Member::RelationShip($mid, $fid);
				if($deposit[0]==2) {// 更改状态
					$sql = "update pft_union_member_info_SE set dstatus=0 where id=$union_id and memberID=$mid limit 1";
					if(!$GLOBALS['le']->query($sql)) exit('{"status":"success","msg":"审核失败"}');
				}
				// abc777\Syslog::write_log("abc777\MemberRelationShip($mid, $fid)","aaa_a");
			}
			if($deposit[0]==1 || $deposit[0]==3){
				
				abc777\Member::RelationShip($fid, $mid);
				// abc777\Syslog::write_log("abc777\MemberRelationShip($fid, $mid)","aaa_a");
				
				// 更改状态
				$sql = "update pft_union_member_info_SE set dstatus=0 where id=$union_id and memberID=$mid limit 1";
				if(!$GLOBALS['le']->query($sql)) exit('{"status":"success","msg":"审核失败"}');
				
				// 自己供应产品的购买产品
				$upd = "update `pft_product_sale_list` set `status`=0,`pids`='A' where aid=$fid and fid=$mid limit 1";
				$GLOBALS['le']->query($upd);
				
				// 3.2配置转分销产品购买权限
				$sql="select * from `pft_p_apply_evolute` where fid=$fid and status=0 and active=1 and sourceid<>$mid and sid<>$mid";
				$GLOBALS['le']->query($sql);
				while($row = $GLOBALS['le']->fetch_assoc()){
					// 供应链存在该分销商
					if(in_array($mid, explode(',', $row['aids']))) continue;
					$evolute[$row['pid']] = array(
						'aids'=>$row['aids'],
						'pid'=>$row['pid'],
						'sid'=>$row['sid'],
						'sourceid'=>$row['sourceid'],
						'lvl'=>$row['lvl'],
					);
				}
				
				$sets = array();// 获取已经设置的记录
				$sql = "select pid,status,id from `pft_p_apply_evolute` where sid=$fid and fid=$mid";
				$GLOBALS['le']->query($sql);
				while($row = $GLOBALS['le']->fetch_assoc()){
					$sets[$row['pid']] = $row;
				}
				
				// 3.3为分销商设置自己可购买转分销产品
				$ins_f = false; $upd_a = array();
				if(count($evolute)){
					$ins = "insert into `pft_p_apply_evolute` (fid,sid,aids,sourceid,pid,lvl,rectime) values ";
					foreach($evolute as $pid=>$data){
						if(isset($sets[$pid])){
							if($sets[$pid]['status']==1){
								$upd_a[] = $sets[$pid]['id'];
							} 
							continue;
						}
						// 没有配置，新增
						$lvl = $data['lvl'] + 1;
						$aids = $data['aids'].','.$fid;
						$ins.="($mid,$fid,'$aids',{$data['sourceid']},$pid,$lvl,now()),";
						$ins_f = true;
					}
					if($ins_f) $GLOBALS['le']->query(rtrim($ins, ','));
				}
				
				if(($size = count($upd_a))){
					$ids = implode(',', $upd_a);
					$upd = "update pft_p_apply_evolute set status=0 where id in ($ids) limit $size";
					$GLOBALS['le']->query($upd);
				}
			}
			
		}
		exit('{"status":"success","msg":"加入成功"}');
		break;
    //显示加入了哪些联盟 状态如何 union.html
    case'show_alliance':
        $sql = "select fid,dstatus,role_pledge from pft_union_member_info_SE where memberID={$_SESSION['sid']} and dstatus<>1";
        $GLOBALS['le']->query($sql);
        while($row=$GLOBALS['le']->fetch_assoc()){
            $role_pledge = explode('|',$row['role_pledge']);
            switch ($row['dstatus']) {
            	case '0':
                    $row['dstatus'] = '正常';
            		break;
                case '1':
                    $row['dstatus'] = '退出';
                    break;
                case '2':
                    $row['dstatus'] = '已申请';
                    break;
                case '3':
                    $row['dstatus'] = '驳回';
                    break;
            }
            $r[] = array(
                'fid'     =>$row['fid'],
                'dstatus' =>$row['dstatus'],//状态
                'ya_money'=>$role_pledge[1] ? ($role_pledge[1])/100: 0 ,//押金
                'ya_status'=>$role_pledge[2] ? $role_pledge[2] : 0,//是否已交押金
            );
        }
        if(count($r)){
            foreach($r as $k => $v){
                $sql = "select dtitle from pft_distributor_union_SE where fid={$v['fid']} limit 1";
                $GLOBALS['le']->query($sql);
                $GLOBALS['le']->fetch_assoc();
                $dtitle = $GLOBALS['le']->f('dtitle');
                $r[$k]['dtitle'] = $dtitle;
            }
        }
        $sta = $r ?'suc' : 'fail';
        exit(json_encode(
            array(
                'sta'=>$sta,
                'list'=>$r
            )
        ));
        break;
    //会员退出 union.html
    case 'union_quite':
        $fid   = $_POST['fid'] + 0;        // 联盟盟主ID
        $mid   = $_SESSION['sid'] + 0;        // 会员ID
        $state = $_POST['status'] + 0;

        goto audit_do;
        break;

    //交押金的弹框里的数据 union.html
    case 'alert_box_pledge':
        include_once("../class/Member.php");
        $m=new Member($s,$_SESSION['sid']);
        $money=$m->money()/100;

        $fid = $_POST['fid']+0;

        $sql = "select cash_pledge from pft_distributor_union_SE where fid=$fid limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $cash_pledge = $GLOBALS['le']->f('cash_pledge');
        $cash_pledge = explode('|',$cash_pledge);

        $sql = "select role_pledge from pft_union_member_info_SE where
         memberID={$_SESSION ['sid']} and fid=$fid limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $role_pledge = $GLOBALS['le']->f('role_pledge');
        $role_pledge = explode('|',$role_pledge);
        $ya_money = ($cash_pledge[$role_pledge[0]-1])/100;

        $enough_money = (float)$money-(float)$ya_money >= 0 ? '1' : '0';
        exit('{
            "sta":"suc",
            "local_money":"'.$money.'",
            "enough_money":'.$enough_money.',
            "ya_money":"'.$ya_money.'"
        }');
        break;
    //处理交押金的数据 union.html
    case 'hand_in_pledge':
        $fid = $_POST['fid']+0;
        $sql = "select role_pledge from pft_union_member_info_SE where
         memberID={$_SESSION ['sid']} and fid=$fid limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $role_pledge = $GLOBALS['le']->f('role_pledge');
        $role_pledge = explode('|',$role_pledge);
        if($role_pledge[2] == 1)
            exit('{"sta":"fail","msg":"已经交过押金了"}');
        include_once("../class/Member.php");
        $m=new Member($s,$_SESSION['sid']);
        $money=$m->money();

        $sql = "select cash_pledge,dtitle from pft_distributor_union_SE where fid=$fid limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $cash_pledge = $GLOBALS['le']->f('cash_pledge');
        $cash_pledge = explode('|',$cash_pledge);
        $ya_money = ($cash_pledge[$role_pledge[0]-1]);

        if((float)$money<(float)$ya_money)
            exit('{"sta":"fail","msg":"你的账户余额不足"}');
        $union_name = $GLOBALS['le']->f('dtitle');
        //盟主加钱
        if($s->PFT_Member_Fund_Modify($fid,$fid,$ya_money,0,0,null,15,0,null,'联盟内会员['.$_SESSION['dname'].']支付押金')){
            //会员扣钱
            if($s->PFT_Member_Fund_Modify($_SESSION['sid'],$_SESSION['sid'],$ya_money,1,0,null,15,0,null,'加入['.$union_name.']联盟的押金')){
                $role_pledge = (string)$role_pledge[0].'|'.(string)$ya_money.'|1';
                $sql = "update pft_union_member_info_SE set role_pledge='$role_pledge' where memberID={$_SESSION ['sid']} and fid=$fid limit 1";
                if($GLOBALS['le']->query($sql))
                    exit('{"sta":"suc","msg":"已成功支付押金"}');
                else{
                    $s->PFT_Member_Fund_Modify($_SESSION['sid'],$_SESSION['sid'],$ya_money,0,0,null,15,0,null,'支付给['.$union_name.']联盟的押金失败,返回资金');
                    $s->PFT_Member_Fund_Modify($fid,$fid,$ya_money,1,0,null,15,0,null,'联盟内会员['.$_SESSION['dname'].'支付押金失败,回扣资金');
                    write_logs('修改联盟会员表pft_union_member_info_SE押金支付记录role_pledge失败,语句:'.$sql);
                    exit('{"sta":"fail","msg":"支付押金失败"}');
                }
            }else{
                $s->PFT_Member_Fund_Modify($fid,$fid,$ya_money,1,0,null,15,0,null,'联盟内会员['.$_SESSION['dname'].'支付押金失败,回扣资金');
                write_logs('会员支付押金失败,fid:'.$_SESSION['sid'].',ya_money:'.$yamoney);
                exit('{"sta":"fail","msg":"支付押金失败"}');
            }
        }else{
            write_logs('盟主收入押金失败,fid:'.$fid.',ya_money:'.$yamoney);
            exit('{"sta":"fail","msg":"支付押金失败"}');
        }
    //盟主给会员退押金 alliance_mem.html
    case 'hand_out_pledge' :
        $mid = $_REQUEST['mid'] + 0;        // 会员ID
        $sql = "select role_pledge from pft_union_member_info_SE where
                memberID=$mid and fid={$_SESSION['sid']} limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $role_pledge = $GLOBALS['le']->f('role_pledge');
        $role_pledge_new = explode('|',$role_pledge);
        if($role_pledge_new[2]!=1){
            exit('{"sta":"fail","msg":"该会员尚未交押金或已退押金"}');
        }
        $ya_money = $role_pledge_new[1];
        $sql = "select dname from pft_member where id=$mid limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $dname = $GLOBALS['le']->f('dname');
        //盟主扣钱
        if($s->PFT_Member_Fund_Modify($_SESSION['sid'],$_SESSION['sid'],$ya_money,1,0,null,15,0,null,'退还给前会员['.$dname.']押金')){
            //会员加钱
            if($s->PFT_Member_Fund_Modify($mid,$mid,$ya_money,0,0,null,15,0,null,'['.$_SESSION['dname'].']联盟退还押金')){
                $role_pledge = $role_pledge_new[0].'|0|0';
                $sql = "update pft_union_member_info_SE set role_pledge=$role_pledge where
                        memberID=$mid and fid={$_SESSION['sid']} limit 1";
                if($GLOBALS['le']->query($sql)){
                    exit('{"sta":"suc","msg":"已成功退还押金"}');
                }else{
                    $s->PFT_Member_Fund_Modify($mid,$mid,$ya_money,1,0,null,15,0,null,'['.$_SESSION['dname'].']联盟退还押金失败,扣除资金');
                    $s->PFT_Member_Fund_Modify($_SESSION['sid'],$_SESSION['sid'],$ya_money,0,0,null,15,0,null,'退还给前会员['.$dname.']押金失败,返回资金');
                    write_logs('修改联盟会员表pft_union_member_info_SE押金支付记录role_pledge失败,语句:'.$sql);
                    exit('{"sta":"fail","msg":"退还押金失败"}');
                }
            }else{
                $s->PFT_Member_Fund_Modify($_SESSION['sid'],$_SESSION['sid'],$ya_money,0,0,null,15,0,null,'退还给前会员['.$dname.']押金失败 返回资金');
                write_logs('会员收入联盟退还的押金失败,fid:'.$mid.',ya_money:'.$yamoney);
                exit('{"sta":"fail","msg":"退还押金失败"}');
            }
        }else{
            write_logs('盟主退还押金失败,fid:'.$_SESSION['sid'].',ya_money:'.$yamoney);
            exit('{"sta":"fail","msg":"退还押金失败"}');
        }
        break;
    default:break;
}



// 确立分销关系
function relationship($mid,$fid){
	$sql = "select id,status from pft_member_relationship where parent_id=$fid and son_id=$mid and son_id_type=0 and ship_type=0 limit 1";
	$GLOBALS['le']->query($sql);
	if($GLOBALS['le']->fetch_assoc()){
		if($GLOBALS['le']->f('status')==1){
			$rid = $GLOBALS['le']->f('id');
			$sql = "update pft_member_relationship set status=0 and restoretime=now() where id=$rid limit 1";
			if($GLOBALS['le']->query($sql)){
				$str_sale = "update pft_product_sale_list set status=0 where fid=$mid and aid=$fid limit 1";
				return $GLOBALS['le']->query($str_sale);	
			}
		}
	}else{
		$sql = "insert into pft_member_relationship set parent_id='$fid',son_id='$mid',son_id_type=0,ship_type=0,rectime=now()";
		if($GLOBALS['le']->query($sql)){
			$str_sale = "insert into pft_product_sale_list (fid,aid,pids) values ($mid,$fid,'')";
			return $GLOBALS['le']->query($str_sale);	
		}

		return false;
	}
	return true;
}



// 加入联盟
function coalize($mid, $fid){
	$sql="select id,memberID from `pft_union_member_info_SE` where fid=$fid and memberID=$mid limit 1";
	$GLOBALS['le']->query($sql);
	if($GLOBALS['le']->fetch_assoc()){// 存在记录
		$aid = $GLOBALS['le']->f('id');
		$upd = "update `pft_union_member_info_SE` set `dstatus`=0 where id=$aid and memberID='$mid' limit 1";
		return $GLOBALS['le']->query($upd);
	}
	$ins = "insert into `pft_union_member_info_SE` (fid,memberID,lvl,dstatus,exps,qx_limit,jointime) values ($fid,$mid,0,0,0,'',now())";
	return $GLOBALS['le']->query($ins);
}

function write_logs($txt,$file='/var/www/html/new/d/logs/union_ya_money.log'){
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX);
    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}


// 数据转义
function _addslashes($data){
	if(is_array($data)){
		foreach($data as $key=>$value){
			$data[$key] = _addslashes($value);
		}
		return $data;
	}
	return addslashes($data);
}
?>